package com.stox.core.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.stox.core.model.exception.StoxException;
import com.stox.design.ApplicationConfigurer;
import com.stox.design.DatabaseConfigurer;
import com.stox.ioc.Container;

public class LifeCycleDao extends AbstractDao 
implements ApplicationConfigurer<Void,Void>{

	public void shutdownDatabase() throws SQLException{
		Connection connection = getNullableConnection();
		if(connection != null && !connection.isClosed()){
			connection.createStatement().execute("shutdown");
		}
	}
	
	@Override
	public Void invoke(Void payload) {
		try {
			String sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.SYSTEM_TABLES where TABLE_TYPE='TABLE'";
			List<String> tableNames = new ArrayList<String>();
			ResultSet rs = getConnection().createStatement().executeQuery(sql);
			while(rs.next()){
				tableNames.add(rs.getString("TABLE_NAME"));
			}
			
			List<DatabaseConfigurer> dbConfigurers = Container.getImplementations(DatabaseConfigurer.class);
			if(dbConfigurers != null && !dbConfigurers.isEmpty()){
				for(DatabaseConfigurer configurer : dbConfigurers){
					configurer.invoke(tableNames);
				}
			}
		} catch (SQLException e) {
			throw new StoxException(e);
		}
		return null;
	}
	
	@Override
	public int getOrder() {
		return 2;
	}
	
}
